<template>
  <span>
     <span>{{this.excel_json}}</span>

  <el-upload
      ref="upload"
      action="https://jsonplaceholder.typicode.com/posts/"
      class="upload-demo"
      accept="xls,xlsx"
      :show-file-list="false"
      :auto-upload="false"
      :multiple="false"
      :on-change="fileOnChange">
    <el-button slot="trigger" size="small" type="primary"  icon="el-icon-plus">处方导入</el-button>

  </el-upload>

</span>
</template>

<script>
var XLSX = require("xlsx");
export default {
  name: "Import",
  data(){
    return{
      excel_json:"",
      fre_data_form:{
        med_num:'',//单味药，药对，三味药
        sort_num:'',
        json:'',
      }
    }
  },
methods:{
  fileOnChange(file, fileList){
    let files = {0:file.raw}
    this.readExcel1(files);
  },
  readExcel1(files) {//表格导入
    var that = this;
    if(files.length<=0){//如果没有文件名
      return false;
    }else if(!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())){

      this.$message.error('上传格式不正确，请上传xls或者xlsx格式');
      return false;
    }
    const fileReader = new FileReader();
    fileReader.onload = (ev) => {
      try {
        const data = ev.target.result;
        const workbook = XLSX.read(data, {
          type: 'binary'
        });

        const wsname1 = workbook.SheetNames[0];//取第一张表
        console.log(wsname1)
        const ws1 = XLSX.utils.sheet_to_json(workbook.Sheets[wsname1]);//生成第一张表的json表格内容
        console.log(ws1.length)
        var medicineArray = new Array();
        for(var i=0;i<ws1.length;i++){
          medicineArray.push(ws1[i].处方)
        }

        console.log(medicineArray)

        this.excel_json = medicineArray;
        this.sendJsonData_to_backend()
        try{
        }catch(err){
          console.log(err)
        }
        this.$refs.upload.value = '';
      } catch (e) {
        return false;
      }
    };
    fileReader.readAsBinaryString(files[0]);
  },

  //将 -----药对，排序个数，excel表json数据传给后端处理
  sendJsonData_to_backend(){
    var that = this
    this.$axios.post('http://localhost:8800/freanalysis', {
      // med_num:that.fre_data_form.med_num,
      // sort_num:that.fre_data_form.sort_num,
      json:that.excel_json,
    })
        .then(function(response) {
          console.log(response)
          // if (response.data.code == 0) {
          //   that.addUserVisible = false
          //   that.requestUser()
          // } else {
          //   that.$message.error(response.data.msg);
          // }
        }).catch(function(error) {

    })
},
}
}

</script>

<style scoped>

</style>
